package com.chaos.system.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chaos.framework.model.dto.ID;
import com.chaos.framework.model.dto.page.PageList;
import com.chaos.framework.model.dto.page.PageQueryDto;
import com.chaos.framework.model.entity.Table;
import com.chaos.framework.model.helper.ConvertHelper;
import com.chaos.framework.model.helper.PageHelper;
import com.chaos.system.api.data.RbacRoleData;
import com.chaos.system.entity.RbacRole;
import com.chaos.system.mapper.RbacRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Jacky.Cui
 * @since 2024-11-13
 */
@Slf4j
@Component
public class RbacRoleService extends ServiceImpl<RbacRoleMapper, RbacRole> {

    public ID insertModel(RbacRoleData data) {
        RbacRole entity = ConvertHelper.convert(data, RbacRole.class);
        return save(entity) ? new ID(entity.getId()) : null;
    }

    public boolean deleteModel(ID data) {
        return removeById(data.getId());
    }

    public boolean updateModelByID(RbacRoleData data) {
        RbacRole entity = ConvertHelper.convert(data, RbacRole.class);
        return update(entity, new UpdateWrapper<RbacRole>().eq(Table.ID, data.getId()));
    }

    public RbacRoleData selectByID(ID data) {
        return ConvertHelper.convert(getOne(new QueryWrapper<RbacRole>().eq(Table.ID, data.getId())), RbacRoleData.class);
    }

    public List<RbacRoleData> selectByData(RbacRoleData data) {
        QueryWrapper<RbacRole> query = new QueryWrapper<>();
        query.orderByDesc(Table.ID);
        return ConvertHelper.convert(list(query), RbacRoleData.class);
    }

    public PageList<RbacRoleData> selectByPage(PageQueryDto<RbacRoleData> pageData) {
        LambdaQueryWrapper<RbacRole> query = new LambdaQueryWrapper<>();
        RbacRoleData data = pageData.getData();
        query.eq(ObjectUtil.isNotNull(data.getId()), RbacRole::getId, data.getId())
                .eq(ObjectUtil.isNotNull(data.getStatus()), RbacRole::getStatus, data.getStatus())
                .eq(ObjectUtil.isNotNull(data.getDataPerm()), RbacRole::getDataPerm, data.getDataPerm())
                .like(ObjectUtil.isNotNull(data.getName()), RbacRole::getName, data.getName());

        query.orderByDesc(RbacRole::getId);
        return PageHelper.pageList(page(PageHelper.page(pageData), query), RbacRoleData.class);
    }

}
